<template>
  <div class="main">
    <div class="topTitle">{{ props.title }}</div>
    <div class="form_content">
      <NScrollbar>
        <NSpin :show="spinShow">
          <div class="content">
            <NForm ref="formRef" require-mark-placement="left" label-placement="left" :rules="rules" :label-width="70"
              :model="formValue" style="width: 1000rem" label-align="right">

              <div class="progressHint" v-if="hint">
                <NIcon size="20" class="iconStyle">
                  <ErrorRound />
                </NIcon>
                <div style="white-space: pre-wrap" v-html="hint"></div>
              </div>
              <div class="progress">
                <div style="display:flex; margin-right: 10rem;">
                  <NIcon :size="20" class="iconStyle">
                    <ApprovalFilled />
                  </NIcon>
                  <span>审批流程</span>
                </div>
                <span style="font-size: 18rem;flex: 1;" :style="{ color: !workFlowList ? 'red' : '#79bb92' }">
                  {{ workFlowList ? workFlowList : '暂无配置流程，请联系管理员进行配置' }}
                </span>
              </div>

              <NSpace justify="space-between">
                <NFormItem label="标题:" path="description">
                  <NInput placeholder="请输入标题" v-model:value="formValue.description" clearable class="commonWidth" />
                </NFormItem>
                <NFormItem label="类型:" path="typeCode">
                  <NSelect v-model:value="formValue.typeCode" clearable :options="typeList" class="commonWidth" />
                </NFormItem>
              </NSpace>

              <NFormItem label="超链接:" path="hyperlink">
                <NInput placeholder="请输入超链接" class="commonWidth" v-model:value="formValue.hyperlink" />
              </NFormItem>

              <!-- 富文本编辑器 -->
              <div style="border: 1px solid #ccc; width: 100%">
                <Toolbar style="border-bottom: 1px solid #ccc" :editor="editorRef" :defaultConfig="toolbarConfig"
                  :mode="mode" />
                <Editor style="height: 300rem; overflow-y: hidden" v-model="formValue.content"
                  :defaultConfig="editorConfig" :mode="mode" @onCreated="handleCreated" />
              </div>
            </NForm>
          </div>
        </NSpin>
      </NScrollbar>
    </div>
  </div>
  <FixedAction>
    <div style="display: flex">
      <NSpace justify="start" style="flex: 0 0 42%">
        <NButton style="width: 78px; color: #5fb17f" ghost @click="goBack">
          <template #icon>
            <img :src="VBackImg" style="width: 25rem; height: 25rem" />
          </template>
          返回
        </NButton>
      </NSpace>

      <NSpace justify="center">
        <NButton type="primary" style="background-color: #5faab1;" @click="confirm(1)" v-if="workFlowList">
          保存草稿
        </NButton>
        <NButton type="primary" @click="confirm(0)" v-if="workFlowList">
          提交申请
        </NButton>
      </NSpace>
    </div>
  </FixedAction>

  <NModal :auto-focus="false" v-model:show="modalVisible">
    <VDialogContent @close="modalVisible = false" @submit="againConfirm" title="保存提示" :loading="loading">
      <div style="width: 300rem; height: 100rem; text-align: center; line-height: 100rem">
        {{ contentContent }}
      </div>
    </VDialogContent>
  </NModal>
</template>

<script setup lang="ts">
import { ref, reactive, watch, shallowRef } from 'vue'
import {
  NSpace,
  NForm,
  NInput,
  NFormItem,
  NButton,
  NScrollbar,
  NSelect,
  NSpin,
  useMessage,
  NModal,
  NIcon,
  NImage,
  type FormInst
} from 'naive-ui'
import router from '@/router'
import { useTagStore } from '@/stores/layout'
import FixedAction from '@/components/FixedAction.vue'
import { sendRequest } from '@/utils/api'
import VDialogContent from '@/views/OA/Common/DialogContent.vue'
import { useRoute } from 'vue-router'
import { workFlow } from '@/enums/workFlow'
import '@wangeditor/editor/dist/css/style.css'
//@ts-ignore
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
//@ts-ignore
import { IEditorConfig } from '@wangeditor/editor'
import { ApprovalFilled } from '@vicons/material'
import VBackImg from '@/assets/images/back.png'
import { getToken } from '@/utils/auth'
import { ErrorRound } from '@vicons/material'

const tags = useTagStore().tags
const message = useMessage()
const route = useRoute()

const props = defineProps({
  title: { type: String, default: () => '党建发文申请' },
  id: { type: [Number, String], default: () => null },
  flag: { type: [Number, String], default: () => null }
})

const spinShow = ref(false)

const formValue = reactive<Record<string, any>>({
  draft: null, //草稿状态
  entityId: null, //流程实体id
  description: null,
  typeCode: null,
  hyperlink: null,
  content: null
})
const rules = {
  description: {
    required: true,
    trigger: ['input', 'blur'],
    validator: (_: any, value: any) => {
      if (!value) return new Error('请填写标题')
      if (value.length > 100) return new Error('标题不得超过100字')
      return true
    }

  },
  typeCode: {
    required: true,
    message: '请选择类型',
    trigger: ['change', 'select']
  }
}

//标签选项
const typeList: any = ref([])
const getType = async () => {
  const [error, res] = await sendRequest({
    module: 'office',
    api: 'roomType',
    override: {
      params: {
        dicCode: 'A19'
      }
    }
  })
  if (error) return message.error(error.message)
  if (res.code !== 0) return message.error(res.msg)
  typeList.value = []
  res.data.map((i: any) => {
    typeList.value.push({
      label: i.dicName,
      value: i.dicCode
    })
  })
}
getType()

// 获取流程id
const hint = ref()
const workFlowList = ref(' ')
const getWorkFlow = async () => {
  const [error, res] = await sendRequest({
    module: 'receiveOrDispatch',
    api: 'workFlow',
    override: {
      params: {
        functionCode: workFlow.DJFWSQLC
      }
    }
  })
  if (error) return
  if (res.code !== 0) return
  formValue.entityId = res.data.entityId
  hint.value = res.data.remark
  workFlowList.value = res.data.workFlowList?.length ? res.data.workFlowList?.map((it: any) => it).join(' → ') : null
}
getWorkFlow()

// 返回
const goBack = () => {
  const index = tags.findIndex((item: any) => item.path === router.currentRoute.value.fullPath)

  tags.splice(index, 1)
  if (tags.length == 0) {
    router.push({ path: '/OA/Workbench/UserDesktop' })
  } else history.back()
}
// 确定
const loading = ref(false)
const formRef = ref<FormInst | null>(null)
const modalVisible = ref(false)
const contentContent = ref()
const confirm = (status: number) => {
  formValue.draft = status
  formRef.value?.validate(async (err) => {
    if (err) return
    if (!formValue.hyperlink && formValue.content == '<p><br></p>')
      return message.error('超链接或正文至少填写一项！')
    contentContent.value = status ? '您确定要保存草稿吗？' : ' 您确定要提交申请吗？'
    modalVisible.value = true
  })
}

const againConfirm = async () => {
  loading.value = true
  if (props.id && !props.flag) {
    const [error, res] = await sendRequest({
      module: 'partAffairs',
      api: 'partBuildUpdate',
      override: {
        data: {
          ...formValue,
          id: props?.id,
          userName: userName.value
        }
      }
    })
    if (error) return message.error(error.message)
    message.success(res.msg)
    goSubmit()
  } else {
    const [error, res] = await sendRequest({
      module: 'partAffairs',
      api: 'partBuildSave',
      override: {
        data: formValue
      }
    })
    if (error) return message.error(error.message)
    message.success(res.msg)
    goSubmit()
  }
  loading.value = false
  modalVisible.value = false
}


//提交完跳转我的提交
const goSubmit = () => {
  const index = tags.findIndex((item: any) => item.path === router.currentRoute.value.fullPath)
  tags.splice(index, 1)
  if (formValue.draft) return router.push({ path: '/OA/UserCenter/Drafts' })
  router.push({ path: '/OA/UserCenter/Submit' })
}

//获取修改详情
const fileList: any = ref([])
const userName = ref()
const getInfo = async () => {
  await getType()
  const [error, res] = await sendRequest({
    module: 'partAffairs',
    api: 'partBuildItem',
    uri: {
      id: props.id as never
    }
  })
  if (error) return message.error(error.message)
  if (res.code !== 0) return message.error(res.msg)
  fileList.value = res.data.fileList
  userName.value = res.data.userName
  Object.keys(formValue).map((it: any) => {
    // @ts-ignore
    formValue[it] = res.data[it]
  })
  await getWorkFlow()
}

// watch(
//   () => route,
//   () => {
//     if (route.path == '/OA/Affairs/BuildEdit' && props.title == '党建发文编辑' && props.id) {
//       getInfo()
//     }
//   },
//   { deep: true, immediate: true }
// )

watch(
  () => props.id,
  () => {
    if (props.title == '党建发文编辑' && props.id) getInfo()
  },
  { deep: true, immediate: true }
)

const mode: any = ref('default')
const editorRef = shallowRef()
const toolbarConfig: any = ref()

const editorConfig: Partial<IEditorConfig> = {
  placeholder: '请输入内容...',
  MENU_CONF: {}
}

const handleCreated = (editor: any) => {
  editorRef.value = editor // 记录 editor 实例，重要！
  editor = Object.seal(editor) // 一定要用 Object.seal() ，否则会报错
  toolbarConfig.value = {
    excludeKeys: [
      '|',
      'emotion', //表情
      'insertVideo', //视频
      'uploadVideo',
      'group-video',
      'insertTable', //插入表格
      'codeBlock', //代码
      'fullScreen' //编辑器全屏
    ]
  }
}

//图片
//@ts-ignore
editorConfig.MENU_CONF['uploadImage'] = {
  fieldName: 'file',
  // server: '/api/common/file/uploadTest',
  server: `${import.meta.env.VITE_API_BASE_URL}/common/annexFile/uploadRichFile`,
  maxFileSize: 100 * 1024 * 1024, // 100M
  // headers: {
  // Accept: 'text/x-json',
  // },
  meta: {
    token: getToken()
  },

  // 跨域是否传递 cookie ，默认为 false
  // withCredentials: true,

  // 超时时间，默认为 10 秒
  // timeout: 5 * 1000, // 5 秒
  // 上传之前触发
  onBeforeUpload(file: File) {
    // TS 语法
    // onBeforeUpload(file) {    // JS 语法
    // file 选中的文件，格式如 { key: file }
    return file

    // 可以 return
    // 1. return file 或者 new 一个 file ，接下来将上传
    // 2. return false ，不上传这个 file
  },
  // 单个文件上传成功之后
  onSuccess(file: File, res: any) {
    // TS 语法
    // onSuccess(file, res) {          // JS 语法
    // console.log(`${file.name} 上传成功`, res)
    message.success(`${file.name} 上传成功`, res)
  },

  // 单个文件上传失败
  onFailed(file: File, res: any) {
    // TS 语法
    // onFailed(file, res) {           // JS 语法
    // console.log(`${file.name} 上传失败`, res)
    message.error(`${file.name} 上传失败`, res)
  },

  // 上传错误，或者触发 timeout 超时
  onError(file: File, err: any, res: any) {
    // TS 语法
    // onError(file, err, res) {               // JS 语法
    console.log(`${file.name} 上传出错`, err, res)
  }
}
</script>

<style scoped lang="scss">
@mixin CommonFont {
  font-size: 16rem;
  font-family: PingFangSC, PingFang SC;
  font-weight: 400;
  color: rgba(0, 0, 0, 0.85);
}

.commonWidth {
  width: 360rem;
}

.main {
  display: flex;
  flex-direction: column;
  width: 100%;
  height: 100%;
  overflow: hidden;

  .topTitle {
    width: 100%;
    height: 64rem;
    border-bottom: 1px solid #fff;
    padding: 20rem;
    margin-bottom: 20rem;
    @include CommonFont;
  }

  .form_content {
    width: 100%;
    height: 100%;
    padding: 0 20rem 0rem;

    .content {
      display: flex;
      align-items: center;
      flex-direction: column;
      width: 100%;
      height: 100%;
      padding: 20rem 0 180rem;
      overflow-y: scroll;
      background-color: #ebeceb;

      .scope {
        display: flex;
        flex-wrap: wrap;
        width: 100%;
        height: 130rem;
        background: #e1e1e1;
        padding: 15rem 20rem;

        .userBox {
          display: flex;
          justify-content: space-between;
          align-items: center;
          width: auto;
          min-width: 150rem;
          height: 40rem;
          background-color: #fff;
          border-radius: 4rem;
          padding: 0 10rem;
          margin-right: 20rem;
        }
      }
    }
  }
}

.iconStyle {
  margin-right: 5rem;
  color: #5fb17f;
}


.progress {
  display: flex;
  align-items: center;
  width: 100%;
  min-height: 50rem;
  background-color: #d5e2d8;
  border-radius: 5rem;
  margin-bottom: 10px;
  padding: 5px 15px;
}

.progressHint {
  display: flex;
  width: 100%;
  padding: 5px 15px;
}

.content::-webkit-scrollbar {
  display: none;
}

:deep(.n-spin-container) {
  width: 100%;
  height: 100%;
}

:deep(.n-scrollbar-container) {
  width: 100%;
  height: 100%;
}

:deep(.n-scrollbar-content) {
  width: 100%;
  height: 100%;
}

:deep(.n-spin-content) {
  width: 100%;
  height: 100%;
}
</style>
